(function (window, $, undefined) {
  'use strict';

  var dictData = {
    status: {
      '101': '启用',
      '102': '禁用',
      '103': '删除'
    },
    cityId: {

    },
    state: {
      '1': '启用',
      '2': '停用'
    }
  };

  var hrData = {};

  main(function () {

    var $tableHr = $('#table-hr');
    util.jqGrid($tableHr, {
      url: ajaxURL.ORGANIZATION + '/company/getCompanyList',
      // datatype: 'json',
      autowidth: true,
      height: $(window).height() - 350,
      multiselect: true,
      multiboxonly: true,
      // shrinkToFit: false,
      colModel: [
        { name: 'kid', key: true, hidden: true },
        { label: '城市', name: 'cityId', width: 50, formatter: function (v) {
          return dictData.cityId[v] || '';
        } },
        {
          label: '人力公司名称', name: 'serviceName', width: 180, formatter: function (v, o, r) {
            return '<a href="javascript:;" class="view" data-id="' + r.kid + '">' + v + '</a>';
          }
        },
        { label: '公司编码', name: 'serviceNo', width: 80 },
        {
          label: '状态', name: 'state', width: 40, formatter: function (v) {
            return dictData.state[v] || '';
          }
        },
        { label: '管理员', name: 'managerName', width: 60 },
        { label: '管理员电话', name: 'managerPhone', width: 100 },
        { label: '负责人', name: 'responsibleName', width: 60 },
        { label: '负责人电话', name: 'responsiblePhone', width: 100 },
        { label: '公司地址', name: 'detailAddress', width: 150 },
        { label: '提供司机等级', name: 'driverLevelId', width: 80 },
        {
          label: '成立时间', name: 'createDate', width: 100, formatter: function (v, o, r) {
          return util.getDate(v);
          }
        },
        {
          label: '录入时间', name: 'createTime', width: 100, formatter: function (v, o, r) {
            return util.getDate(v);
          }
        }
      ],
      loadComplete: function (res) {
        hrData = {};
        if (res && res.data) {
          $.each(res.data, function (_, item) {
            hrData[item.kid] = item;
          });
        }
      },
      pager: '#pager-hr'
    });

    // 获取城市列表
    util.get(ajaxURL.ORGANIZATION + '/city/getCityList?pageNum=1&pageSize=99999', function (res) {
      util.selectHtml($('[name="cityId"]'), res.data, 'cityId', 'name', '请选择');
      $.each(res.data, function (_, item) {
        dictData.cityId[item.cityId] = item.name;
      });
      searchTable();
      $('#btn-search').click(searchTable);
    });

    function searchTable() {
      var data = util.formData('#form-search');
      data.createTime = data.createTime ? util.getTime(data.createTime) : '';
      util.searchGrid($tableHr, data);
    }


    laydate.render({
      elem: '#createTime' //指定元素
    });

    laydate.render({
      elem: '#form-createDate',
      max: 0
    });

    // 查看司机
    $tableHr.on('click', '.view', function () {
      var $this = $(this);
      var id = $this.data('id');

      var data = hrData[id];

      data.createDate = util.getDate(data.createDate);

      util.fillForm('#form-hr-view', data);

      util.layerOpen({
        title: '平台司机管理 - 详情',
        content: $('#layer-hr-view'),
        area: ['1000px', '']
      });

      // // 根据 id 请求数据
      // util.ajax(ajaxURL.ORGANIZATION + '/company/getCompany', { kid: id }, 'GET', util.resCallback(function (res) {
      //   var data = res.data;

      //   data.createDate = util.getDate(data.createDate);

      //   util.fillForm('#form-hr-view', data);

      //   util.layerOpen({
      //     title: '平台司机管理 - 详情',
      //     content: $('#layer-hr-view'),
      //     area: ['1000px', '']
      //   });
      // }));

    });

    var $layerHr = $('#layer-hr-op');
    var $formHr = $('#form-hr-op');

    var $validate = $formHr.validate({
      rules: {
        cityId: { required: true },
        serviceName: { required: true },
        serviceNo: { required: true },
        createDate: { required: true },
        contactPhone: { required: true,isPhone:true },
        managerName: { required: true,stringCheck:true },
        managerPhone: { required: true ,isPhone:true},
        responsibleName: { required: true },
        responsiblePhone: { required: true,isPhone:true },
        detailAddress: { required: true,stringCheck:true },
        mailAddress: { required: true,stringCheck:true },
        status: { required: true }
      },
      messages: {
        cityId: { required: '请选择城市' },
        serviceName: { required: '请输入公司名称' },
        serviceNo: { required: '请输入公司编号' },
        createDate: { required: '请输入设立时间' },
        contactPhone: { required: '请输入联系电话' },
        managerName: { required: '请输入管理员' },
        managerPhone: { required: '请输入管理员电话' },
        responsibleName: { required: '请输入负责人姓名' },
        responsiblePhone: { required: '请输入负责人电话' },
        detailAddress: { required: '请输入公司地址' },
        mailAddress: { required: '请输入文书送达地址' },
        status: { required: '请选择状态' }
      },
      errorPlacement: function (error, element) { //错误信息位置设置方法
        error.appendTo(element.parents('.form-container')); //这里的element是录入数据的对象
      }
    });

    // 新增
    $('#btn-add').click(function () {
      $layerHr.find(':input, button').removeAttr('disabled');
      util.resetForm($formHr);

      util.layerOpen({
        title: '人力服务公司 - 新增',
        content: $layerHr,
        area: ['1000px', ''],
        cancel: function (index) {
          layer.confirm('确定退出当前页面？', {
            btn: ['确定', '再想一想'],
            yes: function (idx) {
              layer.close(index);
              layer.close(idx);
            }
          });
          return false;
        }
      });
    });

    // 修改
    $('#btn-edit').click(util.oneCheck($tableHr, function (id) {
      $layerHr.find(':input, button').removeAttr('disabled');
      util.resetForm($formHr);

      var data = hrData[id];

      data.createDate = util.getDate(data.createDate);

      util.fillForm($formHr, data);

      util.layerOpen({
        title: '人力服务公司 - 修改',
        content: $layerHr,
        area: ['1000px', ''],
        cancel: function (index) {
          layer.confirm('确定退出当前页面？', {
            btn: ['确定', '再想一想'],
            yes: function (idx) {
              layer.close(index);
              layer.close(idx);
            }
          });
          return false;
        }
      });

      // util.ajax(ajaxURL.ORGANIZATION + '/company/getCompany', {kid: id}, 'GET', util.resCallback(function (res) {
      //   var data = res.data;

      //   data.createDate = util.getDate(data.createDate);

      //   util.fillForm($formHr, data);

      //   util.layerOpen({
      //     title: '人力服务公司 - 修改',
      //     content: $layerHr,
      //     area: ['1000px', ''],
      //     cancel: function (index) {
      //       layer.confirm('确定退出当前页面？', {
      //         btn: ['确定', '再想一想'],
      //         yes: function (idx) {
      //           layer.close(index);
      //           layer.close(idx);
      //         }
      //       });
      //       return false;
      //     }
      //   });
      // }));

    }));

    // 停用
    $('#btn-stop').click(util.oneCheck($tableHr, function (id) {
      var data = hrData[id];

      if (+data.state === 2) {
        return util.tip.warn('该公司已经处于停用状态！');
      }

      layer.confirm('确定停用该人力服务公司？停用后可能影响部分已绑定该公司的司机，请谨慎操作', {
        btn: ['确定', '再想一想']
      }, function () {
        data.state = 2;
        updateCompany(data);
      });
    }));

    // 启用
    $('#btn-active').click(util.oneCheck($tableHr, function (id) {
      var data = hrData[id];

      if (+data.state === 1) {
        return util.tip.warn('该公司已经处于启用状态！');
      }

      layer.confirm('确定启用该人力服务公司？', {
        btn: ['确定', '再想一想']
      }, function () {
        data.state = 1;
        updateCompany(data);
      });

    }));

    function updateCompany(data) {
      util.ajax(ajaxURL.ORGANIZATION + '/company/updateCompany', JSON.stringify(data), 'POST', util.resCallback(function (res) {
        layer.closeAll();
        util.tip.success('操作成功');
        $tableHr.trigger('reloadGrid');
      }));
    }

    // 保存操作
    $('#btn-save').click(function () {
      var data = util.formData($formHr);
      console.log(data);

      if ($validate.form()) {

        data.licenseImg = '649c38917ae84d5a9ab0ec97a4649328';
        data.driverLevelId = '1';
        data.companyCityId = data.cityId;
        data.createDate = util.getTime(data.createDate);
        data.state = 1;

        var url = ajaxURL.ORGANIZATION + (data.kid === '' ? '/company/addCompany' :'/company/updateCompany');

        util.ajax(url, JSON.stringify(data), 'POST', util.resCallback(function (res) {
          layer.closeAll();
          util.tip.success('操作成功');
          $tableHr.trigger('reloadGrid');
        }));

      }
    });

  });


})(window, jQuery);
